﻿using Microsoft.AspNetCore.Http;
using System.Net;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using VisionCloud.Domain.Common;
using VisionSurface.Web.Authorize;

namespace VisionSurface.Web.Middleware
{
    /// <summary>
    /// 授权验证失败后返回401自定义内容
    /// </summary>
    public class CustomAuthorizationMiddleware
    {
        private readonly RequestDelegate next;

        public CustomAuthorizationMiddleware(RequestDelegate next)
        {
            this.next = next;
        }

        public async Task InvokeAsync(HttpContext context)
        {
            await next(context);

            //删除云端缓存Token的时候，JwtToken鉴权通过了，但授权失败，此时中间得到的StatusCode为403
            if (context.Response.StatusCode == (int)HttpStatusCode.Unauthorized || context.Response.StatusCode == (int)HttpStatusCode.Forbidden)
            {
                context.Response.ContentType = "application/json";

                var authorizationFailedContext = context.Features.Get<AuthorizationFailedContext>();

                var apiResult = new ApiResult
                {
                    Code = AjaxCode.Unauthorized,
                    Message = authorizationFailedContext?.Message ?? "没有访问权限"
                };

                context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                await context.Response.WriteAsync(JsonSerializer.Serialize(apiResult), Encoding.UTF8);
            }
        }
    }
}
